﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Configuration;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;

namespace MachineBuildingSystem
{
    public partial class DeliveryOperationUC : XtraUserControl
    {
        private DataTable m_BindDT;
        private OrderInfo m_Order = null;
        //生产线与ID对照
        private Dictionary<string, long> m_ProductLineDic = new Dictionary<string, long>();

        private long m_SelectedProductLineId = 0;
        //所有车牌号列表
        private string m_HaveCarCodeStr = "";
        //所有司机列表
        private string m_HaveDriverStr = "";

        private int m_ExcuteFormulaWay = 0;
        //类型，0：4500访问SQLServer，1：3800
        private int m_Type = 0;
        //系统时间
        private DateTime m_SystemTime = DateTime.Now;

        public DeliveryOperationUC()
        {
            InitializeComponent();
        }

        private void rgpType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rgpType.SelectedIndex == 0)
                this.xtraTabControl1.SelectedTabPage = xtraTabPageEach;
            else
                this.xtraTabControl1.SelectedTabPage = xtraTabPageBatch;
        }


        private void DeliveryOperationUC_Load(object sender, EventArgs e)
        {
            ContextMenu emptyMenu = new ContextMenu();
            mruEditCarCode.Properties.ContextMenu = emptyMenu;
            mruEditDriver.Properties.ContextMenu = emptyMenu;
            mruEditProductLine.Properties.ContextMenu = emptyMenu;
            spProductNumber.Properties.ContextMenu = emptyMenu;
            spRecycleNumber.Properties.ContextMenu = emptyMenu;
            spSendNumber.Properties.ContextMenu = emptyMenu;
            InitBindDT();
        }

        private void InitBindDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("Autoid");
            m_BindDT.Columns.Add("Checked", typeof(bool));
            m_BindDT.Columns.Add("carCode");
            m_BindDT.Columns.Add("driverName");
            m_BindDT.Columns.Add("workingId");
            m_BindDT.Columns.Add("workingName");

            m_BindDT.Columns.Add("productQuantity");
            m_BindDT.Columns.Add("recoveredQuantity");
            m_BindDT.Columns.Add("deliQuantity");
            m_BindDT.Columns.Add("deliDate");
        }

        #region 对外方法
        //填充批量信息
        public void FillInfo(OrderInfo order, DateTime systemTime)
        {
            m_ExcuteFormulaWay = int.Parse(ConfigurationManager.AppSettings["ExcuteFormulaWay"].ToString());
            m_Type = int.Parse(ConfigurationManager.AppSettings["MachineType"].ToString());
            m_checkStatus = false;
            m_Order = order;
            m_SystemTime = systemTime;
            rgpType.SelectedIndex = 0;
            this.xtraTabControl1.SelectedTabPage = xtraTabPageEach;
            gdcProduct.DataSource = null;
            //填充逐条信息
            mruEditCarCode.Text = "";
            mruEditDriver.Text = "";
            mruEditProductLine.Text = "";
            dateEditDelDate.EditValue = systemTime;
            InitMruEditCarCode();
            InitMruEditDriver();
            InitMruEditProductLine();
            mruEditProductLine.SelectedItem =
                CommonHelper.FindDataInfoByKey(mruEditProductLine, order.workingId);
            spProductNumber.EditValue = 0;
            spRecycleNumber.EditValue = 0;
            //批次信息
            if (m_ExcuteFormulaWay == 0)
                return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
        }

        //获取信息
        public DeliverySaveData GetDeliverySaveData()
        {
            DeliverySaveData deliverySaveData = new DeliverySaveData ();
            deliverySaveData.carCode = mruEditCarCode.Text.Trim();
            deliverySaveData.driverName = mruEditDriver.Text.Trim();
            deliverySaveData.workingId = m_SelectedProductLineId;
            deliverySaveData.workingName = mruEditProductLine.Text.Trim();
            deliverySaveData.productQuantity = this.spProductNumber.Value;
            deliverySaveData.recoveredQuantity = this.spRecycleNumber.Value;
            deliverySaveData.deliDate = Convert.ToDateTime(dateEditDelDate.EditValue.ToString());
            return deliverySaveData;
        }

        public void UpdateConfig(string carCode, string driver)
        {
            try
            {
                //更新车牌号配置文件
                if (!m_HaveCarCodeStr.Split(',').Contains(carCode))
                {
                    m_HaveCarCodeStr += "," + carCode;
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfa.AppSettings.Settings["CarCodeStr"].Value = m_HaveCarCodeStr;
                    cfa.Save();
                    ConfigurationManager.RefreshSection("appSettings");
                }
                //更新司机配置文件
                if (!m_HaveDriverStr.Split(',').Contains(driver))
                {
                    m_HaveDriverStr += "," + driver;
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfa.AppSettings.Settings["Drivers"].Value = m_HaveDriverStr;
                    cfa.Save();
                    ConfigurationManager.RefreshSection("appSettings");
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("更新车牌号和司机配置文件异常：" + ex.ToString());
            }
           
        }

        //清空界面
        public void ClearForm()
        {
            if (rgpType.SelectedIndex == 0)
            {
                mruEditCarCode.Text = "";
                mruEditDriver.Text = "";
                mruEditProductLine.Text = "";
                dateEditDelDate.EditValue = m_SystemTime;
                mruEditProductLine.SelectedItem =
                    CommonHelper.FindDataInfoByKey(mruEditProductLine, m_Order.workingId);
                spProductNumber.EditValue = 0;
                spRecycleNumber.EditValue = 0;
            }
            else
            {
                //List<string> list = new List<string>();
                //foreach (DeliverySaveData delivery in dataList)
                //    list.Add(delivery.Autoid.ToString());

                //DataTable tempDT = m_BindDT.Clone();
                //foreach (DataRow dr in m_BindDT.Rows)
                //{
                //    if (!list.Contains(dr["Autoid"].ToString()))
                //        tempDT.Rows.Add(dr.ItemArray);
                //}
                //m_BindDT.Clear();
                //if (tempDT != null)
                //{
                //    foreach (DataRow dr in tempDT.Rows)
                //    {
                //        m_BindDT.Rows.Add(dr.ItemArray);
                //    }
                //}
                //gdcProduct.DataSource = m_BindDT;
            }
        }
        #endregion

        #region 线程
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                    return;
                if (e.Error != null)
                {
                    MessageBox.Show(this, e.Error.Message);
                    return;
                }
                m_BindDT.Clear();
                gdcProduct.DataSource = m_BindDT;
                List<DeliverySaveData> list = e.Result as List<DeliverySaveData>;
                if (list == null || list.Count == 0)
                    return;
                foreach (DeliverySaveData data in list)
                    m_BindDT.Rows.Add(data.Autoid, false, data.carCode, data.driverName, data.workingId, data.workingName, 
                        data.productQuantity, 0, data.productQuantity, data.deliDate.ToString("yyyy-MM-dd HH:mm:ss"));
                gdcProduct.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定批量发货信息异常：" + ex.ToString());
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<DeliverySaveData> list = new List<DeliverySaveData>();
            try
            {
                if (m_Type == 0 || m_Type == 1)
                {
                    string sql = "";
                    if(m_Type == 0)
                        sql = "select Autoid, TruckCode, DriverName,ProductLine,Volume from  ProdMasterData  where modetag = 2 and jobno = '" + m_Order.orderCode + "' order by TruckCount";
                    else
                        sql = "select Autoid, TruckCode, DriverName,ProductLine,Volume from  ProdMasterData  where modetag = 1 and jobno = '" + m_Order.orderCode + "' order by TruckCount";
                    DataTable dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            DeliverySaveData data = new DeliverySaveData();
                            data.Autoid = long.Parse(dr["Autoid"].ToString());
                            data.orderId = m_Order.id;
                            data.carCode = dr["TruckCode"].ToString();
                            data.driverName = dr["DriverName"].ToString();
                            data.workingName = dr["ProductLine"].ToString();
                            if (m_ProductLineDic.ContainsKey(data.workingName.Trim()))
                                data.workingId = Convert.ToInt64(m_ProductLineDic[data.workingName.Trim()]);
                            data.productQuantity = dr["Volume"] == DBNull.Value ? 0 : decimal.Parse(dr["Volume"].ToString());
                            data.deliDate = m_SystemTime;
                            list.Add(data);
                        }
                    }
                }
                else if (m_Type == 2)
                {
 
                }
            }
            catch
            {
                throw;
            }
            e.Result = list;
        }
        #endregion

        //初始化生产线下拉框
        private void InitMruEditProductLine()
        {
            try
            {
                m_ProductLineDic = new Dictionary<string, long>();
                string str = ConfigurationManager.AppSettings["ProductLines"].ToString();
                string[] productLineArr = str.Split(',');
                if (productLineArr.Length == 0)
                    return;
                mruEditProductLine.Properties.Items.Clear();
                foreach (string productLine in productLineArr)
                {
                    string[] strArr = productLine.Split('/');
                    DataInfo data = new DataInfo();
                    data.Id = Convert.ToInt64(strArr[0]);
                    data.Value = strArr[1];
                    mruEditProductLine.Properties.Items.Add(data);
                    m_ProductLineDic.Add(data.Value, data.Id);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化生产线下拉框数据异常：" + ex.Message);
            }
        }

        //初始化司机下拉框
        private void InitMruEditDriver()
        {
            try
            {
                mruEditDriver.Properties.Items.Clear();
                m_HaveDriverStr = ConfigurationManager.AppSettings["Drivers"];
                foreach (string driver in m_HaveDriverStr.Split(','))
                    mruEditDriver.Properties.Items.Add(driver);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化司机下拉框数据异常：" + ex.Message);
            }
        }

        private void InitMruEditCarCode()
        {
            try
            {
                mruEditCarCode.Properties.Items.Clear();
                m_HaveCarCodeStr = ConfigurationManager.AppSettings["CarCodeStr"];
                foreach (string carCode in m_HaveCarCodeStr.Split(','))
                    mruEditCarCode.Properties.Items.Add(carCode);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化车牌号下拉框数据异常：" + ex.Message);
            }
        }

        private void mruEditProductLine_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mruEditProductLine.SelectedItem == null || mruEditProductLine.SelectedItem == "")
                m_SelectedProductLineId = -1;
            else
                m_SelectedProductLineId = ((DataInfo)mruEditProductLine.SelectedItem).Id;
        }

        private void sp_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue != null && e.NewValue.ToString().StartsWith("-"))
            {
                e.Cancel = true;
            }
        }

        private void spProductNumber_EditValueChanged(object sender, EventArgs e)
        {
            spSendNumber.EditValue = Convert.ToDecimal(spProductNumber.EditValue)
                + Convert.ToDecimal(spRecycleNumber.EditValue);
        }

        private void spRecycleNumber_EditValueChanged(object sender, EventArgs e)
        {
            spSendNumber.EditValue = Convert.ToDecimal(spProductNumber.EditValue)
              + Convert.ToDecimal(spRecycleNumber.EditValue);
        }

        private void gdvProduct_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (gdvProduct.RowCount > 0 && e.RowHandle >= 0)
            {
                if (gdvProduct.FocusedColumn.FieldName == "recoveredQuantity")
                {
                    try
                    {
                          int handle = e.RowHandle;
                          decimal productQuantity =
                              Convert.ToDecimal(this.gdvProduct.GetRowCellValue(handle, gdcProductQuantity));
                          decimal recoveredQuantity = 
                              Convert.ToDecimal(this.gdvProduct.GetRowCellValue(handle, gdcRecoveredQuantity));
                          decimal deliQuantity = productQuantity + recoveredQuantity;
                          this.gdvProduct.GetDataRow(handle)["DeliQuantity"] = deliQuantity;              
                    }
                    catch (Exception ex)
                    {
                        LogHelper.error("填充回收数量异常：" + ex.ToString());
                    }
                }
            }
        }

        private bool m_checkStatus = false;
        private void gdvProduct_Click(object sender, EventArgs e)
        {
            if (CommonHelper.ClickGridCheckBox(this.gdvProduct, "Checked", m_checkStatus))
            {
                m_checkStatus = !m_checkStatus;
            }
        }

        private void gdvProduct_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "Checked")
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                CommonHelper.DrawCheckBox(e, m_checkStatus);
                e.Handled = true;
            }
        }

        private void gdcProduct_DataSourceChanged(object sender, EventArgs e)
        {
            GridColumn column = this.gdvProduct.Columns.ColumnByFieldName("Checked");
            if (column != null)
            {
                column.OptionsColumn.ShowCaption = false;
                column.ColumnEdit = new RepositoryItemCheckEdit();
            }
        }

        private void gdvProduct_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}
